package com.hyzh.latte.vehicle.socket;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.coffee.socketio.handler.SocketioConnectHandler;
import com.corundumstudio.socketio.SocketIOClient;
import com.hyzh.latte.vehicle.nezha.NezhaClient;
import com.hyzh.latte.vehicle.nezha.NezhaSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author: songkui
 * @since: 2024/3/21 0:14
 */
@Service
@Slf4j
public class SocketConnectHandler implements SocketioConnectHandler {


    @Override
    public void connect(Map<String, List<String>> params, SocketIOClient client) {
        log.info("Connect: session {}; params {} ",  client.getSessionId(), JSON.toJSONString(params));

        List<String> userIdList = params.get("userId");
        List<String> tokenList = params.get("token");
        List<String> parkList = params.get("park");
        if (CollectionUtil.isEmpty(parkList) || CollectionUtil.isEmpty(tokenList) || CollectionUtil.isEmpty(userIdList)){
            log.error("connect failure:  please required parameter ");
            return;
        }

        String userId =  userIdList.get(0);
        String token = tokenList.get(0);
        String park = parkList.get(0);

        NezhaClient nezhaClient = new NezhaClient();
        nezhaClient.setClient(client);
        nezhaClient.setToken(token);
        nezhaClient.setUserId(userId);
        nezhaClient.setParkCode(park);
        nezhaClient.setSessionId(client.getSessionId().toString());

        NezhaSessionManager.getInstance().putClient(nezhaClient);
        log.info("Connect: success [sessionId {};  userId{}]", client.getSessionId(), userId);

    }
}
